﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Nero_demo
{
    class WaitStruct
    {
        public ResourceUser user;
        public int priority;
        public EventWaitHandle waitEvent;

        public WaitStruct(ResourceUser _user, int _prio, EventWaitHandle _we)
        {
            user = _user;
            priority = _prio;
            waitEvent = _we;
        }
    };
    class Resource
    {
        public Resource(string _name, int _count = 1)
        {
            name = _name;
            count = _count;

            queueLock = new Mutex();
            ownerLock = new Mutex();

            owners = new ResourceUser[count];

            for (int i = 0; i < count; i++)
            {
                owners[i] = null;
            }

            waitQueue = new List<WaitStruct>();
        }
        // block to get resource
        public int Require(ResourceUser user, int prio = 0)
        {
            int ret = -1;

            LogHelper.Record("Proc " + user.Name + " require res #" + name + "Res");

            ownerLock.WaitOne();
            while ((ret = SearchForAvailable(user)) == -1)
            {
                EventWaitHandle waitEvent = InsertToQueue(user, prio);
                ownerLock.ReleaseMutex();
                // Pending the test
                waitEvent.WaitOne();
                // Resource ready, re-lock and search
                ownerLock.WaitOne();
            }

            owners[ret] = user;
            user.AddResource(this, ret);
            ownerLock.ReleaseMutex();
            LogHelper.Record("Proc " + user.Name + " get res #" + name + "Res");
            user.ResourceGot();
            return ret;
        }
        // No block, -1 for no available source
        public int TryToRequire(ResourceUser user)
        {
            int ret = -1;

            LogHelper.Record("Proc " + user.Name + " try to require res #" + name + "Res");

            ownerLock.WaitOne();
            if ((ret = SearchForAvailable(user)) == -1)
            {
                ownerLock.ReleaseMutex();
                return -1;
            }

            owners[ret] = user;
            user.AddResource(this, ret);
            ownerLock.ReleaseMutex();
            LogHelper.Record("Proc " + user.Name + " get res #" + name + "Res");
            user.ResourceGot();
            return ret;
        }
        public void Release(int id = 0)
        {
            ownerLock.WaitOne();
            // S_ASSERT(owners[id] != NULL);
            LogHelper.Record("Proc " + owners[id].Name + " release res #" + name + "Res");
            owners[id].DelResource(this, id);
            // owners[id] = NULL;    

            WaitStruct ws = PopQueue();

            if (null != ws.user)
            {
                LogHelper.Record("Proc " + ws.user.Name + " will get res #" + name + "Res");
                // To make sure always has a running test proc at least
                owners[id] = ws.user;
                ws.waitEvent.Set();
            }
            else
            {
                owners[id] = null;
            }
            ownerLock.ReleaseMutex();
        }
        public bool SetCount(int cnt)
        {
            ownerLock.WaitOne();

            for (int i = 0; i < count; i++)
            {
                if (owners[i] != null)
                {
                    ownerLock.ReleaseMutex();
                    return false;
                }
            }

            count = cnt;
            ownerLock.ReleaseMutex();
            return true;
        }

        private int SearchForAvailable(ResourceUser user)
        {
            for (int i = 0; i < count; i++)
            {
                if (owners[i] == user)
                {
                    return i;
                }
            }
            for (int i = 0; i < count; i++)
            {
                if (owners[i] == null)
                {
                    return i;
                }
            }
            return -1;
        }
        private EventWaitHandle InsertToQueue(ResourceUser user, int prio)
        {
            queueLock.WaitOne();

            int targetIndex = 0;
            for (int i = 0; i < waitQueue.Count; i++)
            {
                if (waitQueue[i].priority < prio)
                {
                    targetIndex = i;
                    break;
                }
            }
            LogHelper.Record("Proc " + user.Name + " wait for #" + name + "Res");
            EventWaitHandle waitEvent = new AutoResetEvent(false);
            waitQueue.Insert(targetIndex, new WaitStruct(user, prio, waitEvent));
            queueLock.ReleaseMutex();

            return waitEvent;
        }
        private WaitStruct PopQueue()
        {
            queueLock.WaitOne();

            if (waitQueue.Count == 0)
            {
                queueLock.ReleaseMutex();
                return new WaitStruct(null, 0, null);
            }
            else
            {
                WaitStruct ws = waitQueue[0];
                ResourceUser retUser = ws.user;
                waitQueue.RemoveAt(0);

                LogHelper.Record("Proc " + retUser.Name + " is removed from #" + name + "Res");
                queueLock.ReleaseMutex();
                return ws;
            }
        }
        private ResourceUser[] owners;
        private string name;
        private int count;
        private Mutex queueLock;
        private Mutex ownerLock;
        private List<WaitStruct> waitQueue;

        private const int MAX_RESOURCE_NUM = 100;
    }
}
